
package com.joysuch.wwyt.risk.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.BpBaseUserBean;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.core.bean.SimpleListBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.SimpleSelectListService;
import com.joysuch.wwyt.repeatsubmit.NoRepeatSubmit;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskDistrictEvaluation;
import com.joysuch.wwyt.risk.entity.vo.DistrictDeleteCheckVO;
import com.joysuch.wwyt.risk.service.RiskDistrictEvaluationService;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.risk.service.RiskEvaluationControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@Api(tags = "双预防-风险分区")
@RequestMapping("/risk/district")
public class RiskDistrictController {

    private static final Logger logger = LoggerFactory.getLogger(RiskDistrictController.class);

    @Autowired
    private RiskDistrictService districtService;
    @Autowired
    private RiskDistrictEvaluationService districtEvaluationService;
    @Autowired
    private SimpleSelectListService simpleSelectListService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao departDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private RiskEvaluationControlService controlService;

    @PostMapping("add")
    @NoRepeatSubmit(paramNames = "code,name")
    public Object addDistrict(@RequestBody @Valid RiskDistrictSaveBean districtBean) throws Exception {
        districtService.add(districtBean);
        return ResultBean.success("");
    }

    @PostMapping("update")
    public Object updateDistrict(@RequestBody @Valid RiskDistrictSaveBean districtBean) throws Exception {
        if (districtBean.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        districtService.update(districtBean);
        return ResultBean.success("");
    }

    @RequestMapping("page")
    public Object page(Pageable page, RiskDistrictListSearchBean condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "createTime");
            Page<RiskDistrict> distrct = districtService.findByPage(page, condition);
            List<RiskDistrictListBean> list = new ArrayList<>(distrct.getContent().size());
            boolean stableCorFlag = controlService.getStableCorFlag();
            for (RiskDistrict d : distrct) {
                RiskDistrictListBean convert = convert(d, stableCorFlag);
                //2.10区域华为列表展示固有风险
                convert.setRiskLevel(d.getStableRiskLevel());
                convert.setRiskLevelName(RiskLevels.findRiskLevelName(d.getStableRiskLevel()));
                list.add(convert);
            }
            return ResultBean.pageData(list, distrct.getTotalElements());
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "查询区域列表失败");
        }
    }

    @GetMapping("getById")
    @ApiOperation("区域的按id查询")
    public ResultBean getById(Long id) {
        RiskDistrict riskDistrict = districtService.findById(id);
        RiskDistrictListBean convert = convert(riskDistrict, controlService.getStableCorFlag());
        return ResultBean.success(convert);
    }

    @RequestMapping("workflow-page")
    public Object workFlowPage(Pageable page, RiskDistrictListSearchBean condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "createTime");
            Page<RiskDistrict> district = districtService.findByPage(page, condition);
            List<RiskDistrictListBean> list = new ArrayList<>(district.getContent().size());
            boolean stableCorFlag = controlService.getStableCorFlag();
            for (RiskDistrict d : district) {
                list.add(convert(d, stableCorFlag));
            }
            return ResultBean.pageData(list, district.getTotalElements());
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "查询区域列表失败");
        }
    }

    // 风险区域列表
    @RequestMapping("permission-list")
    public Object getPermissionSimpleList() {
        try {
            // simpleList
            List<SimpleSelectListBean> name = districtService.getDistrictSimpleList();
            return ResultBean.success(name);
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "查询区域列表失败");
        }
    }

    // 风险区域列表
    @RequestMapping("simple-list")
    public Object getSimpleList() {
        try {
            // simpleList
            List<SimpleSelectListBean> name = districtService.getDistrictSimpleList();
//            List<SimpleSelectListBean> name = simpleSelectListService.list(RiskDistrict.class, "name");
            return ResultBean.success(name);
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "查询区域列表失败");
        }
    }

    //未用到的接口
    // 风险区域列表
    @RequestMapping("simple-page")
    public Object getSimplePage(Pageable pageList) {
        try {
            // simpleList
            Page<SimpleSelectListBean> name = simpleSelectListService.page(pageList, RiskDistrict.class, "name");
            return ResultBean.pageData(name);
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "查询区域列表失败");
        }
    }

    private RiskDistrictListBean convert(RiskDistrict d, boolean stableCorFlag) {
        RiskDistrictListBean bean = new RiskDistrictListBean();
        bean.setId(d.getId());
        bean.setCode(d.getCode());
        bean.setName(d.getName());
        bean.setCreateTime(SimpleDateFormatCache.getYmdhms().format(d.getCreateTime()));
        Optional<BaseUser> obu = baseUserDao.findById(d.getCreateBy());
        if (obu.isPresent()) {
            bean.setCreator(obu.get().getRealName());
        }
        bean.setRemark(d.getRemark());
        bean.setCoordinates(d.getCoordinates());
        if (d.getResponsibleDept() != null) {
            String deptName = departDao.getNameById(Long.valueOf(d.getResponsibleDept()));
            bean.setResponsibleDeptName(deptName);
            bean.setResponsibleDept(d.getResponsibleDept());
        }
        bean.setRiskLevel(d.getStableRiskLevel());
        bean.setRiskLevelName(RiskLevels.findRiskLevelName(d.getStableRiskLevel()));
       // bean.setEvaluationState(stableCorFlag ? d.getEvaluationState() : null);
        bean.setEvaluationState(stableCorFlag ? null : 1);
        bean.setType(d.getType());
        bean.setTypeName(baseTypeGroupItemDao.findNameById(d.getType()));
        if (StringUtils.isNotBlank(d.getResponsibleUser())) {
            List<Long> userIds = JSONArray.parseArray(d.getResponsibleUser(), Long.class);
            List<SimpleListBean> repUserBeanList = new ArrayList<>();
            for (Long userId : userIds) {
                SimpleListBean sBean = new SimpleListBean();
                Optional<BaseUser> obur = baseUserDao.findById(userId);
                if (obur.isPresent()) {
                    sBean.setName(obur.get().getRealName());
                }
                sBean.setId(userId);
                repUserBeanList.add(sBean);
            }
            bean.setResponsibleUseBeanList(repUserBeanList);
        }
        if (StringUtils.isNotBlank(d.getAreaHelpers())) {
            List<Long> userIds = JSONArray.parseArray(d.getAreaHelpers(), Long.class);
            List<SimpleListBean> repUserBeanList = new ArrayList<>();
            for (Long userId : userIds) {
                SimpleListBean sBean = new SimpleListBean();
                Optional<BaseUser> obur = baseUserDao.findById(userId);
                if (obur.isPresent()) {
                    sBean.setName(obur.get().getRealName());
                }
                sBean.setId(userId);
                repUserBeanList.add(sBean);
            }
            bean.setAreaHelpersList(repUserBeanList);
        }
        return bean;
    }

    //删除风险分区
    @GetMapping("delete")
    @RequiresPermissions("risk:district:delete")
    public Object delete(Long id) {
        try {
            districtService.delete(id);
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && StringUtils.isNotEmpty(e.getMessage())) {
                List<DistrictDeleteCheckVO> list = Lists.newArrayList();
                DistrictDeleteCheckVO vo = JSONObject.parseObject(e.getMessage(), DistrictDeleteCheckVO.class);
                list.add(vo);
                return ResultBean.fail(e.getCode(), "", list);
            } else {
                return ResultBean.fail(e.getCode(), e.getMessage());
            }
        }
        return ResultBean.success("");
    }

    //批量删除风险分区
    @PostMapping("deleteBylist")
    @RequiresPermissions("risk:district:deleteBylist")
    public Object deleteByList(@RequestBody LongListBean bean) {
        districtService.deleteByList(bean);
        return ResultBean.success("");
    }


    // 获取区域评估状态列表
    @RequestMapping("evaluation-district-list")
    public Object stableRiskList(Pageable page, Integer state) {
        page = PageDataUtils.addOrderByDesc(page, "code");
        Page<RiskDistrictEvaluationListBean> pageData = districtService.findDistrictEvluationByPage(page, state);
        return ResultBean.pageData(pageData.getContent(), pageData.getTotalElements());
    }

    // 获取区域风险评估列表
    @RequestMapping("stable-risk-list")
    public Object stableRiskList(Pageable page, RiskDistrictStableRiskListSearchBean condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "code");
            Page<RiskDistrictStableRiskListBean> pageData = districtService.findByPage(page, condition);
            return ResultBean.pageData(pageData.getContent(), pageData.getTotalElements());
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "删除区域失败");
        }
    }

    // 获取区域风险评估详情

    /**
     * 获取区域评估详情
     *
     * @param riskDisctrictId 区域ID
     * @param searchHistory   true:查询历史，false:不查询历史
     * @return
     */
    @RequestMapping("get-stable-risk-evaluation-detail")
    public Object getStableRiskEvaluationDetail(Long riskDisctrictId, boolean searchHistory) {
        try {
            RiskDistrictStableRiskQueryBean data = districtService.findStableRiskEvaluationDetail(riskDisctrictId,
                    searchHistory);
            return ResultBean.success(data);
        } catch (Exception e) {
            logger.error("获取区域风险评估详情出错", e);
            return ResultBean.fail(101, "获取区域风险评估详情出错");
        }
    }

    // 执行评估
    // 1. 增加评估记录
    // 2. 关联区域评估记录为当前记录
    @RequestMapping("do-evaluation")
    public Object doEvaluation(@Valid RiskDistrictEvaluation evaluation) {
        try {
            districtEvaluationService.add(evaluation);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("生成区域失败", e);
            return ResultBean.fail(101, "删除区域失败");
        }
    }

    @RequestMapping("getResponsibleAndHelpers")
    public ResultBean getResponsibleAndHelpers(Long id){
        List<BpBaseUserBean> responsibleAndHelpers = districtService.getResponsibleAndHelpers(id);
        return ResultBean.success(responsibleAndHelpers);
    }

}
